import express, { Request, Response } from "express";
import AppDataSource from "../../data-source";
import { Question } from "../../entity/many_to_many/Question";
import { Category } from "../../entity/many_to_many/Category";

const router = express.Router();

/**
 * @swagger
 * /api/manytomany/questions:
 *   get:
 *     summary: 获取所有问题
 *     tags: [Many_To_Many]
 *     responses:
 *       200:
 *         description: 成功获取问题列表
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/many_to_many_question'
 *       500:
 *         description: 内部服务器错误
 */
router.get("/manytomany/questions", async (req: Request, res: Response) => {
  try {
    const questions = await AppDataSource.getRepository(Question).find({
      relations: { categories: true },
    });
    res.json(questions);
  } catch (error) {
    console.error("获取问题列表时出错:", error);
    res.status(500).send({ message: "内部服务器错误" });
  }
});

/**
 * @swagger
 * /api/manytomany/questions/{id}:
 *   get:
 *     summary: 获取单个问题
 *     tags: [Many_To_Many]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 问题ID
 *     responses:
 *       200:
 *         description: 成功获取问题详情
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/many_to_many_question'
 *       404:
 *         description: 问题未找到
 *       500:
 *         description: 内部服务器错误
 */
router.get("/manytomany/questions/:id", async (req: Request, res: Response) => {
  try {
    const questionId = Number(req.params.id);

    const question = await AppDataSource.getRepository(Question).findOne({
      where: { id: questionId },
      relations: { categories: true },
    });

    if (!question) {
      res.status(404).send({ message: "问题未找到" });
      return;
    }

    res.send(question);
  } catch (error) {
    console.error("获取问题详情时出错:", error);
    res.status(500).send({ message: "内部服务器错误" });
  }
});

/**
 * @swagger
 * /api/manytomany/questions:
 *   post:
 *     summary: 创建问题
 *     tags: [Many_To_Many]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/many_to_many_createquestionrequest'
 *           examples:
 *             Example1:
 *               value:
 *                 title: "Example Question 1"
 *                 text: "This is the first example question."
 *                 categoryIds: [1, 2]
 *             Example2:
 *               value:
 *                 title: "Example Question 2"
 *                 text: "This is the second example question."
 *                 categoryIds: [3]
 *     responses:
 *       201:
 *         description: 问题创建成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/many_to_many_question'
 *       500:
 *         description: 内部服务器错误
 */
router.post("/manytomany/questions", async (req: Request, res: Response) => {
  try {
    const questionRepository = AppDataSource.getRepository(Question);
    const categoryRepository = AppDataSource.getRepository(Category);

    const { title, text, categoryIds } = req.body;

    const question = new Question();
    question.title = title;
    question.text = text;

    if (categoryIds && Array.isArray(categoryIds)) {
      question.categories = await categoryRepository.findByIds(categoryIds);
    }

    await questionRepository.save(question);
    res.status(201).send(question);
  } catch (error) {
    console.error("创建问题时出错:", error);
    res.status(500).send({ message: "内部服务器错误" });
  }
});

/**
 * @swagger
 * /api/manytomany/questions/{id}:
 *   put:
 *     summary: 更新问题
 *     tags: [Many_To_Many]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 问题ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/many_to_many_updatequestionrequest'
 *           examples:
 *             Example1:
 *               value:
 *                 title: "Updated Question 1"
 *                 text: "This is the updated first example question."
 *                 categoryIds: [1, 3]
 *             Example2:
 *               value:
 *                 title: "Updated Question 2"
 *                 text: "This is the updated second example question."
 *                 categoryIds: []
 *     responses:
 *       200:
 *         description: 问题更新成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/many_to_many_question'
 *       404:
 *         description: 问题未找到
 *       500:
 *         description: 内部服务器错误
 */
router.put("/manytomany/questions/:id", async (req: Request, res: Response) => {
  try {
    const questionRepository = AppDataSource.getRepository(Question);
    const categoryRepository = AppDataSource.getRepository(Category);

    const questionId = Number(req.params.id);
    const { title, text, categoryIds } = req.body;

    let question = await questionRepository.findOne({
      where: { id: questionId },
      relations: { categories: true },
    });

    if (!question) {
      res.status(404).send({ message: "问题未找到" });
      return;
    }

    question.title = title;
    question.text = text;

    if (categoryIds && Array.isArray(categoryIds)) {
      question.categories = await categoryRepository.findByIds(categoryIds);
    } else {
      question.categories = [];
    }

    await questionRepository.save(question);
    res.send(question);
  } catch (error) {
    console.error("更新问题时出错:", error);
    res.status(500).send({ message: "内部服务器错误" });
  }
});

/**
 * @swagger
 * /api/manytomany/questions/{id}:
 *   delete:
 *     summary: 删除问题
 *     tags: [Many_To_Many]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 问题ID
 *     responses:
 *       200:
 *         description: 问题删除成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *       404:
 *         description: 问题未找到
 *       500:
 *         description: 内部服务器错误
 */
router.delete(
  "/manytomany/questions/:id",
  async (req: Request, res: Response) => {
    try {
      const questionRepository = AppDataSource.getRepository(Question);

      const questionId = Number(req.params.id);

      const question = await questionRepository.findOne({
        where: { id: questionId },
      });

      if (!question) {
        res.status(404).send({ message: "问题未找到" });
        return;
      }

      await questionRepository.remove(question);
      res.status(200).send({ message: "问题删除成功" });
    } catch (error) {
      console.error("删除问题时出错:", error);
      res.status(500).send({ message: "内部服务器错误" });
    }
  }
);

export default router;
